import { useParams } from "react-router-dom";
import { getQuestionService } from "../service/questions";
import { useRequest } from "ahooks";
import { useEffect } from "react";
import { useDispatch } from "react-redux";
import { resetComponents } from "../store/componentsReducer";
import { resetPageInfo } from "../store/pageInfoReducer";
function useLoadQuestionData() {
  const { id = "" } = useParams();
  const dispatch = useDispatch();
  //ajax加载
  const { data, loading, error, run } = useRequest(
    async (id: string) => {
      if (!id) throw new Error("没有问卷 id");
      const data = await getQuestionService(id);
      return data;
    },
    {
      manual: true,
    }
  );
  //根据获取的data，设置redux
  useEffect(() => {
    if (!data) return;
    const {
      title = "",
      desc = "",
      js = "",
      css = "",
      bgUrl = "",
      isPublished = false,
      componentList = [],
    } = data;
    //获取默认的selectedID
    let selectedId = " ";
    if (componentList.length > 0) {
      selectedId = componentList[0].fe_id;
    }
    dispatch(
      resetComponents({
        componentList,
        selectedId,
        copiedComponent: null,
      })
    );
    //把pageInfo存储到redux store中
    dispatch(resetPageInfo({ title, desc, js, css, bgUrl, isPublished }));
  }, [data]);

  //根据获取的id,执行ajax
  useEffect(() => {
    run(id);
  }, [id]);

  return { loading, error };
}

export default useLoadQuestionData;
